﻿using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
//using System.Data.SqlClient;
using Microsoft.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp7
{
    public class SqlServerlogger : ILogger
    {
        private readonly string connectionString;
        public SqlServerlogger(string connectionString)
        {
            this.connectionString = connectionString;
        }
        public IDisposable? BeginScope<TState>(TState state) where TState : notnull
        {
            return null;
        }

        public bool IsEnabled(LogLevel logLevel)
        {
            return true;
        }

        public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
        {
            if (!IsEnabled(logLevel))
            {
                return;
            }
            // 格式化日志消息
            var message = formatter(state, exception);
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                string sql = "INSERT INTO Logs(Message, LogLevel, CreatedTime) VALUES (@message, @logLevel, @createdTime)";

                SqlCommand sqlCommand = new SqlCommand(sql, connection);
                SqlParameter[] sqlParameters = new SqlParameter[] {
                    new SqlParameter()
                    {
                        ParameterName="@message",
                        Value=message
                    },
                    new SqlParameter()
                    {
                        ParameterName="@logLevel",
                        Value=logLevel.ToString()
                    },
                    new SqlParameter()
                    {
                        ParameterName="@createdTime",
                        Value=DateTime.Now
                    },
                };
                sqlCommand.Parameters.AddRange(sqlParameters);
                connection.Open();
                sqlCommand.ExecuteNonQuery();
                connection.Close();
            }
        }
    }
}
